<?php
class Items extends MY_Controller {
	var $currentPage = 'items';
	var $caption = 'Item';
	var $action = '';
	
	public function index($start=0,$limit=10)
	{
		$this->load->library('pagination');
		$config['base_url'] = base_url() . 'admin/items/index/';
		$config['total_rows'] = count($this->mItem->getAllEntries());
		$config['uri_segment'] = 4;
		$config['per_page'] = $limit;
		$config['cur_page'] = $this->uri->segment(4);
		$config['use_page_numbers'] = true;
		$config['num_links'] = 5;
		$config['first_link'] = '<span class="page-far-left">';
		$config['last_link'] = '<span class="page-far-right">';
		/*$config['next_link'] = '<span class="page-right">';
		$config['prev_link'] = '<span class="page-left">';*/
		//$config['full_tag_open'] = '<p>';
		//$config['full_tag_close'] = '</p>';
		$this->pagination->initialize($config);
	    //$this->team is autoload at Controller's constructor
	    $data['itemList'] = $this->mItem->limit($limit,(($start-1) * $limit));
	    $data['pagination'] = $this->pagination->create_links();
	  
	    $this->loadAdminPage($data);
	}
	
	public function create(){
		$data = array();
		$this->action = 'add';
		$data['categories'] = $this->mCategory->getAllEntries();

		$this->loadAdminPage($data);
	}
	
	public function edit($id){
		$item = $this->mItem->getEntryById($id);
		$item_image = $this->mItemImage->getByItemId($id);
		
		if(count($item) == 0) {
			show_error("Invalid item", 500, "Invalid data");
		}
		
		$data['item'] = $item[0];
		$data['image'] = isset($item_image) ? $item_image : null;
		$data['categories'] = $this->mCategory->getAllEntries();
		
		$this->action = 'edit';
		$this->id = $item[0]->id;
		$this->loadAdminPage($data);
	}
	
	
	 function add(){
	 	
    	$item = $this->mItem;
    	
    	$item->category_id = $this->input->post('category_id',TRUE);
    	$item->name = trim($this->input->post('item_name',TRUE));
    	$item->price = trim($this->input->post('price',TRUE));
    	$item->code = trim($this->input->post('code',TRUE));
    	$item->description = trim($this->input->post('description',TRUE));
    	$item->sku = trim($this->input->post('sku',TRUE));
    	$item->available_qty = trim($this->input->post('available_qty',TRUE));
    	
    	if(!is_integer($item->category_id))
    		$item->category_id = 0;
    	
    	//strlen($item->category_id) == 0 || 
    	if(strlen($item->code) == 0 || strlen($item->name) == 0 || strlen($item->price) == 0
    		|| strlen($item->sku) == 0 || strlen($item->available_qty) == 0) {
    			$this->message = INSERT_ERROR;
    			$this->index();
    			return;
    	}
    	
    	if(count($this->mItem->findByItemCode($item->code)) != 0) {
    		$this->message = HAS_DUPLICATE;
    		$this->index();
    		return;
    	}
    	
		$this->load->library('upload');
		
    	$this->createDirectory();
		
    	$item->db->trans_start();
    	$item->insert();			
		$item->id = $item->db->insert_id();
    	
    	$imageId = $this->input->post('image_id',TRUE);
    	
    	$ctr = 0;
    	
    	$itemImage = $this->mItemImage;
    	
    	for($x = 0; $x < count($imageId); $x++) {
    		
    		$fileArrayIndex = "image" . ($x+1);	
    		
    		if($_FILES[$fileArrayIndex]['error'] == 0) {
	    		$itemImage = $this->uploadImage($fileArrayIndex, $itemImage, $item);
    			if(!is_object($itemImage)) {
					$this->message = $itemImage;
			    	$this->edit($item->id);
			    	return;
				}
	    		$itemImage->insert();
    		}		
    	}		
    	    		
		$this->db->trans_complete();
		
		//var_dump($this->db->trans_status());
		
     	$this->index();
    }
	
    function update() {
    	$item = $this->mItem;
    	
    	$item->id = $this->input->post('id',TRUE);
    	$item->category_id = $this->input->post('category_id',TRUE);
    	$item->name = trim($this->input->post('item_name',TRUE));
    	$item->price = trim($this->input->post('price',TRUE));
    	$item->code = trim($this->input->post('code',TRUE));
    	$item->description = trim($this->input->post('description',TRUE));
    	$item->sku = trim($this->input->post('sku',TRUE));
    	$item->available_qty = trim($this->input->post('available_qty',TRUE));
    	
    	if(!is_integer($item->category_id))
    		$item->category_id = 0;
    	
    	
    	//strlen($item->category_id) == 0
        if(strlen($item->code) == 0 || strlen($item->name) == 0 || strlen($item->price) == 0
    		|| strlen($item->sku) == 0 || strlen($item->available_qty) == 0) {
    			$this->message = UPDATE_ERROR;
    			$this->edit($item->id);
    			return;
    	}
    	
    	if(count($this->mItem->findByItemCodeOfOthers($item->id,$item->code)) != 0) {
    		$this->message = HAS_DUPLICATE . " code.";
    		$this->edit($item->id);
    		return;
    	}
    	
    	$item->update();
    		
    	/** upload image **/
		$this->load->library('upload');
    	
		$this->createDirectory();
		
    	$imageId = $this->input->post('image_id',TRUE);
    	$ctr = 0;
    	
    	$itemImage = $this->mItemImage;
    	
    	for($x = 0; $x < count($imageId); $x++) {
    		
    		$fileArrayIndex = "image" . ($x+1);
    		
    		/** update image **/
    		if(is_numeric($imageId[$x]) && strlen($imageId[$x]) > 0) {
	    		$image = $itemImage->getEntryById($imageId[$x]);

	    		if($_FILES[$fileArrayIndex]['error'] == 0) {
	    			$itemImage = $this->uploadImage($fileArrayIndex,$image, $item);

					if(!is_object($itemImage)) {
						$this->message = $itemImage;
			    		$this->edit($item->id);
			    		return;
					}
					
	    			if(file_exists($image[0]->thumbnail))
	    				unlink($image[0]->thumbnail);
	    			
		    		if(file_exists($image[0]->original))
		    			unlink($image[0]->original);
	    			
	    			$itemImage->update();
	    		}
    		} else {
    		/** insert image **/
    			if($_FILES[$fileArrayIndex]['error'] == 0) {
	    			$itemImage = $this->uploadImage($fileArrayIndex, $itemImage, $item);
    				if(!is_object($itemImage)) {
						$this->message = $itemImage;
			    		$this->edit($item->id);
			    		return;
					}
	    			$itemImage->insert();
    			}
    		}
    	}
    	
    	$this->edit($item->id);
    }
	
	public function delete($id){
		$this->mItem->delete($id);
		$this->index();
	}
	
	private function uploadImage($key, $itemimage, $item) {
		
		if(!$this->upload->do_upload($key)) {
			return $this->upload->display_errors();
		}
		
		/** get the details of uploaded image **/
		$image = $this->upload->data();
		
		$itemImage = $this->mItemImage;
		
		$itemImage->filename = $image['file_name'];
		
		if(is_object($itemimage)) {
    		$itemImage->item_id = $item->id;
    		$itemImage->id = $itemimage->id;
			$itemImage->original = ORIGINAL_IMAGE_PATH.$itemImage->filename;
			$itemImage->thumbnail = THUMBNAIL_IMAGE_PATH.$itemImage->filename;
		} else if(is_array($itemimage)) {
    		$itemImage->item_id = $item->id;
    		$itemImage->id = $itemimage[0]->id;
			$itemImage->original = ORIGINAL_IMAGE_PATH.$itemImage->filename;
			$itemImage->thumbnail = THUMBNAIL_IMAGE_PATH.$itemImage->filename;
		}

        $config=array(
            'source_image'=>$itemImage->original,
            'new_image'=>$itemImage->thumbnail,
            'maintain_ration'=>TRUE,
            'width'=>150,
            'height'=>100
        );
            
        $this->load->library('image_lib');
           
        $this->image_lib->clear();
        $this->image_lib->initialize($config);
        if(!$this->image_lib->resize())
        	return $this->image_lib->display_errors();		
        	
        return $itemImage;
	}
	
	
	private function createDirectory() {
		if(!is_dir(IMAGE_PATH))
	    	mkdir(IMAGE_PATH,DIR_WRITE_MODE,TRUE);
    	
	   	if(!is_dir(ORIGINAL_IMAGE_PATH))
	    	mkdir(ORIGINAL_IMAGE_PATH,DIR_WRITE_MODE,TRUE);
	    	
		if(!is_dir(THUMBNAIL_IMAGE_PATH))
			mkdir(THUMBNAIL_IMAGE_PATH,DIR_WRITE_MODE,TRUE);
		
	}
}